//
//  SINAStuActivityAddTargetInputViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/24.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINAStuActivityAddTargetInputViewController.h"
#import "SINACircularBeadUtils.h"
#import "SINASelectTimeTableViewCell.h"
#import "SINACalendarUtils.h"

@interface SINAStuActivityAddTargetInputViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITextField *inputTargerField;
@property (weak, nonatomic) IBOutlet UILabel *textNumberFlagLabel;
@property (weak, nonatomic) IBOutlet UIView *inputBackgroundView;
@property (weak, nonatomic) IBOutlet UISwitch *timeSwitch;

//选择时间
@property (weak, nonatomic) IBOutlet UIView *selectTimeView;
@property (weak, nonatomic) IBOutlet UILabel *selectTimeShowView;
@property (weak, nonatomic) IBOutlet UIImageView *selectTimeIconView;
@property (weak, nonatomic) IBOutlet UIView *showSelectTimeView;
@property (weak, nonatomic) IBOutlet UITableView *selectTimeTableview;


@property(assign,nonatomic) BOOL  isShowSelectTime;

@property (weak, nonatomic) IBOutlet UILabel *commitLabel;

@property(strong,nonatomic) NSString *currentSelectTime;

@end

@implementation SINAStuActivityAddTargetInputViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title=@"添加小目标";
    
    [super initBackItem];
    UIView *rightView =[[UIView alloc]initWithFrame:CGRectMake(0,0,40,50)];
    UIButton *rightButton =[[UIButton alloc]initWithFrame:CGRectMake(0,0,40,45)];
    [rightButton addTarget:self action:@selector(saveDataFunction) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:rightButton];
    [rightButton setTitle:@"保存" forState:UIControlStateNormal];
//    UIBarButtonItem *rightButtonView = [[UIBarButtonItem alloc]initWithCustomView:rightView ];
    //self.navigationItem.rightBarButtonItem=rightButtonView;
    
    [self.inputTargerField addTarget:self action:@selector(searchTextFieldChangeAction:)   forControlEvents:UIControlEventEditingChanged];
    
    
    self.inputTargerField.tag=100;
    self.inputTargerField.delegate=self;
    
    [SINACircularBeadUtils makeCircularBead:4 andView: self.inputBackgroundView andIsSetBackground:NO];
    [SINACircularBeadUtils makeCircularBead:4 andView: self.selectTimeView andIsSetBackground:NO];
     [SINACircularBeadUtils makeCircularBead:4 andView: self.selectTimeTableview andIsSetBackground:NO];
    self.timeSwitch.transform = CGAffineTransformMakeScale(0.5, 0.5);
    
   
    //self.timeSwitch.tintColor = [UIColor redColor];
    self.timeSwitch.onTintColor = baseSelectColor;
    //self.timeSwitch.thumbTintColor = [UIColor yellowColor];
    //self.timeSwitch.backgroundColor = [UIColor purpleColor];
    //添加事件监听
    [self.timeSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.selectTimeView andWithBlick:^(UIView *view) {
        DLog(@"选择时间");
        [self showSelectTimeFunction];
        
    }];
    
    self.currentSelectTime=@"30min";
    
    self.selectTimeTableview.delegate=self;
    self.selectTimeTableview.dataSource=self;
    self.selectTimeTableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.selectTimeTableview.backgroundColor=[UIColor colorWithHexString:@"#ffffff"];
    self.selectTimeTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    self.commitLabel.backgroundColor = baseSelectColor;
    [SINACircularBeadUtils makeCircularBead:22 andView: self.commitLabel andIsSetBackground:NO];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.commitLabel andWithBlick:^(UIView *view) {
        [self saveDataFunction];
    }];
    
}

-(void)showSelectTimeFunction{
    if (self.isShowSelectTime) {
        self.currentSelectTime=@"";
        // 再隐藏
        [self hindSelectTimeFunction];
    } else {
        // 再显示
        self.isShowSelectTime=YES;
        self.showSelectTimeView.hidden=NO;
        self.selectTimeView.backgroundColor= baseSelectColor;
        self.selectTimeIconView.image=[UIImage imageNamed:@"向上箭头白"];
        self.selectTimeShowView.textColor=[UIColor whiteColor];
        self.currentSelectTime=@"30min";
        self.selectTimeShowView.text=@"30min";
        
        CGRect preFrame =self.selectTimeTableview.frame;
        preFrame.size.height=240;
        [UIView animateWithDuration:0.3 animations:^{
            self.selectTimeTableview.frame=preFrame;
        } completion:^(BOOL finished) {
            
        }];
    }
}
-(void)hindSelectTimeFunction{
    self.isShowSelectTime=NO;
    self.selectTimeIconView.image=[UIImage imageNamed:@"下箭头"];
    self.selectTimeView.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
    self.selectTimeShowView.textColor=[UIColor colorWithHexString:@"#2a2a2a"];
    
    CGRect preFrame =self.selectTimeTableview.frame;
    preFrame.size.height=0;
    [UIView animateWithDuration:0.3 animations:^{
        self.selectTimeTableview.frame=preFrame;
    } completion:^(BOOL finished) {
        self.showSelectTimeView.hidden=YES;
    }];
}
-(void)switchAction:(id)sender
{
    UISwitch *switchButton = (UISwitch*)sender;
    BOOL isButtonOn = [switchButton isOn];
    if (isButtonOn) {
        DLog(@"开");
        self.selectTimeView.hidden=NO;
        self.currentSelectTime=@"30min";
        self.selectTimeShowView.text=@"30min";
        
        CGRect preFrame =self.selectTimeView.frame;
        preFrame.size.height=40;
        [UIView animateWithDuration:0.3 animations:^{
            self.selectTimeView.frame=preFrame;
        } completion:^(BOOL finished) {
            
        }];
    }else {
        DLog(@"关");
       
        self.showSelectTimeView.hidden=YES;
        self.currentSelectTime=@"";
        self.selectTimeShowView.text=@"30min";
        
        self.selectTimeIconView.image=[UIImage imageNamed:@"下箭头"];
        self.selectTimeView.backgroundColor=[UIColor colorWithHexString:@"#eeeeee"];
        self.selectTimeShowView.textColor=[UIColor colorWithHexString:@"#2a2a2a"];
        
        CGRect preFrame =self.selectTimeView.frame;
        preFrame.size.height=0;
        [UIView animateWithDuration:0.3 animations:^{
            self.selectTimeView.frame=preFrame;
        } completion:^(BOOL finished) {
             self.selectTimeView.hidden=YES;
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)searchTextFieldChangeAction: (id)sender
{
    NSInteger textInteger =10-[self.inputTargerField.text length];
    
    self.textNumberFlagLabel.text=[NSString stringWithFormat:@"%ld",(long)textInteger];
    
}
#pragma mark -- 设定可输入10位数
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSInteger maxLength = 10;//设置限制字数
    
    if (textField.tag == 100) {
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        if (toBeString.length > maxLength && range.length!=1){
            textField.text = [toBeString substringToIndex:maxLength];
            
            return NO;
            
        }
        
    }
    
    return YES;
}
//提交保存数据
-(void)saveDataFunction{
    
    NSString *targetString =self.inputTargerField.text;
    
    if (targetString.length==0) {
        NSString *message =@"请输入小目标";
        WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }

    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:targetString forKey:@"title"];
    [dict setObject:self.model.activityUid forKey:@"organizeuuid"];
    
    BOOL isButtonOn = [self.timeSwitch isOn];
    if (isButtonOn) {
        //
        DLog(@"定时 %@",self.currentSelectTime);
        
        
        NSInteger activityStartTime = [self.model.activityStartTime integerValue];
        NSInteger activityEndTime = [self.model.activityStopTime integerValue];
        //当前时间
        NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
        
        NSInteger useTotalTime=0;
        if ([self.currentSelectTime isEqualToString:@"1min"]) {
            useTotalTime =1;
        }else  if ([self.currentSelectTime isEqualToString:@"5min"]) {
            useTotalTime =5;
        }else  if ([self.currentSelectTime isEqualToString:@"10min"]) {
            useTotalTime =10;
        }else  if ([self.currentSelectTime isEqualToString:@"30min"]) {
            useTotalTime =30;
        }else  if ([self.currentSelectTime isEqualToString:@"1hour"]) {
            useTotalTime =60;
        }else  if ([self.currentSelectTime isEqualToString:@"2hour"]) {
            useTotalTime =120;
        }
       
        
        if (currentTime<activityStartTime) {
            DLog(@"活动未开始");
            //小目标的时间范围     活动结束时间-当前时间
        }else if(currentTime>=activityStartTime&&currentTime<=(activityEndTime)){
            DLog(@"活动中");
            //活动结束时间-当前时间
        }else if(currentTime>=activityEndTime&&currentTime<=(activityEndTime+30*60*1000)){
            //活动已结束
            //活动结束时间-当前时间
        }else{
            //超时
            return;
        }
        NSInteger flagTime = activityEndTime+30*60*1000 - currentTime;
        
        if (useTotalTime*60*1000>=flagTime) {
            [YPXToastView showToastViewWithText:@"定时时长不可超出活动结束时间" andDuration:3 andParentView:self.view];
            return;
        }
        
        [dict setObject:self.currentSelectTime forKey:@"plantime"];
        
    }
    
     [self startLoading];
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userActivityAddTargetUrl] withParamters:dict2 success:^(id responseData) {
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            //添加成功
            [YPXToastView showToastViewWithText:@"添加成功" andDuration:1 andParentView:weakSelf.inputTargerField ];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //创建通知
                NSNotification *notification =[NSNotification notificationWithName:@"addTargetNotification" object:nil userInfo:dict];
                // 通过 通知中心 发送 通知
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
                
            });
        }else{
            NSString *message =responseData[@"message"];
            [YPXToastView showToastViewWithText:message andDuration:3 andParentView:self.view];
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        
        [YPXToastView showToastViewWithText:@"添加失败 网络异常" andDuration:3 andParentView:self.view];
    }];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SINASelectTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINASelectTimeTableViewCell"];
    
    if (cell == nil) {
        cell= [[[NSBundle mainBundle]loadNibNamed:@"SINASelectTimeTableViewCell" owner:nil options:nil] firstObject];
        
    }
    
    
    cell.cellTimeClickBlock = ^(NSString *item) {
        
        //选择时间
        [self hindSelectTimeFunction];
        self.selectTimeShowView.text=item;
        self.currentSelectTime = item;
    };
    
    //SINASelectTimeTableViewCell
    switch (indexPath.row) {
        case 0:
            cell.string =@"1min";
            break;
        case 1:
            cell.string =@"5min";
            break;
        case 2:
            cell.string=@"10min";
            break;
        case 3:
            cell.string =@"30min";
            break;
        case 4:
            cell.string =@"1hour";
            break;
        case 5:
            cell.string =@"2hour";
            break;
        default:
            break;
    }
    
    
    
    return cell ;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

@end
